// pages/user/shopingCart/shopingCart.js
//集成appjs中方法及属性
var http = require('../../service/http.js');//请求类
var util = require('../../utils/util.js');//工具类
const app = getApp();
var rd_session = '';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //----------登录操作-----------------
    showLogin: false,//展示登录页
    pageUrl: '',//跳转地址
    productItems: "",
    pTitle: '',
    isEdit: false,
    isChecked: false,
    isCheckedAll: false,
    cartProducts: [],//购物车所有商品列表
    product: {},
    productId:'',//商品itemid
    isAuthorization: app.data.isAuthorization,//是否已授权
    //----------暂存购物车商品信息-------------------
    itemId: '',//暂存购物车商品id 
    skuId: '',//skuid
    count: 1,//购物车数量
    stock: 0,  //默认库存
    //---------购物车编辑操作------------------------
    todoList: [],//被操作的商品集合
    totalCount: 0,//商品总额
    onProducts: [],//被选中的商品（用于计算总数额）
    selectNum: 0,//被选中商品数量
    compareNum:0,//用于比较购物车数量的库存
    //---------店铺信息-----------------------------
    shopName:'',//店铺名称
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
  },
  onShow: function () {
    let that = this;
    rd_session = wx.getStorageSync('rd_session');
    that.setData({
      shopName: app.data.shopName
    })
    that.onPullDownRefresh();
  },
  //------------加载购物车列表----------------------------
  showCartList: function () {
    //请求购物车数据
    let that = this;
    console.log('showCartList--rd_session=' + rd_session);

    http.getReq('/weixin/cart/showCartList', {
      rdSession: rd_session
    }, function (res) {
      console.log(res);
      if (res.ret) {
        console.log("购物车列表--" + res.data.value.length)
        let cartProducts = res.data.value;
        //------------所有商品被选中状态置0 未选中
        for (let p = 0; p < cartProducts.length; p++) {
          cartProducts[p].isSelect = 0;
        }
        //---------------设置商品信息-------------------------------
        that.setData({
          cartProducts: cartProducts,
        })
        console.log(that.data.cartProducts);
      }else{
        console.log('需要登录');
      }
    });
   
  },
  onReady: function () {

  },
  selectAll: function (e) {//改变全选

    let cartProducts = this.data.cartProducts;//所有购物车商品
    let isCheckedAll = this.data.isCheckedAll;//是否是全选
    let totalCount = 0;
    let selectNum = 0;

    //-------------判断是否是编辑状态---------------------------
    let isEdit = this.data.isEdit;

    if (isCheckedAll) {//是否全选中状态 全选置0
      for (let p = 0; p < cartProducts.length; p++) {
        cartProducts[p].isSelect = 0
      }
      isCheckedAll = false
      selectNum = 0;
    } else {
      if (isEdit) {//编辑状态 且为全未选中
        for (let p = 0; p < cartProducts.length; p++) {
          cartProducts[p].isSelect = 1
        }
        selectNum = cartProducts.length;
      } else {//非编辑状态 且为全未选中
        for (let p = 0; p < cartProducts.length; p++) {
          if (cartProducts[p].isValid == 1) {//有效改变商品状态
            cartProducts[p].isSelect = 1
            selectNum = selectNum + 1
          } else {//失效商品取消选中
            cartProducts[p].isSelect = 0
          }
        }
      }
      isCheckedAll = true
    }

    for (let p = 0; p < cartProducts.length; p++) {
      if (cartProducts[p].isValid == 1 && cartProducts[p].isSelect == 1) {
        totalCount = totalCount + parseFloat(cartProducts[p].count * cartProducts[p].price)
      }
    }

    console.log("selectNum" + selectNum);
    //更新商品数据及总额
    this.setData({
      cartProducts: cartProducts,
      totalCount: totalCount.toFixed(2),
      isCheckedAll: isCheckedAll,
      selectNum: selectNum
    })
  },
  editCart: function () {//编辑购物车
    //清空全选状态--------------------------------------

    let isCheckedAll = this.data.isCheckedAll;
    let cartProducts = this.data.cartProducts;

    for (let p = 0; p < cartProducts.length; p++) {
      cartProducts[p].isSelect = 0;
    }

    this.setData({
      isEdit: true,
      todoList: [],//初始化编辑列表
      isCheckedAll: false,
      cartProducts: cartProducts,
      selectNum: 0,
      totalCount: 0.00
    })
  },
  saveCart: function (e) {//完成编辑保存--交互
    let that = this;
    let todoList = that.data.todoList;//编辑商品列表
    let cartProducts = that.data.cartProducts;//购物车列表
    let selectNum = 0;
    if (todoList.length > 0) {
      
      http.getReq('/weixin/cart/updateCart', {
        todoList: todoList,
        rdSession: rd_session
      }, function (res) {
        if (res.ret) {
          //计算商品总额
          cartProducts = res.data.value;
          let isCheckedAll = that.data.isCheckedAll;
          if (cartProducts.length == 0) {
            isCheckedAll = false;
          }
          //计算总额以及商品选中个数
          for (let p = 0; p < cartProducts.length; p++) {
            if (cartProducts[p].isSelect == 1 && cartProducts[p].isValid == 1) {
              selectNum = parseInt(selectNum) + 1
            }
            if (cartProducts[p].isValid == 0) {//无效商品取消选中
              cartProducts[p].isSelect = 0;
            }
          }
          console.log(cartProducts);
          //更新商品数据
          that.setData({
            cartProducts: cartProducts,
            isCheckedAll: isCheckedAll,
            selectNum: selectNum
          })
          console.log("编辑后商品长度" + that.data.cartProducts.length);
        } else {
          console.log('编辑失败');
        }
      });
     
    } else {//没有编辑的商品
      for (let p = 0; p < cartProducts.length; p++) {
        if (cartProducts[p].isSelect == 1 && cartProducts[p].isValid == 1) {
          selectNum = parseInt(selectNum) + 1
        }
        if (cartProducts[p].isValid == 0) {//失效商品不选
          cartProducts[p].isSelect = 0
        }
      }
    }
    console.log("selectNum" + selectNum);
    this.setData({
      isEdit: false,
      cartProducts: cartProducts,
      selectNum: selectNum
    })
  },

  minCount: function (e) {
    console.log("减少" + e);
    let count = e.currentTarget.dataset.count;//原购物车商品数量
    let index = e.currentTarget.dataset.index;//商品列表下标
    let cartProducts = this.data.cartProducts;//所有购物车商品
    let todoList = this.data.todoList;//被操作的商品集合

    if (count > 1) {
      count = parseInt(count) - 1;
    } else {
      count = 1;
      wx.showToast({
        title: '购买数量不能小于1',
        icon: 'none'
      })
    }
    //改变被选中商品数量
    cartProducts[index].count = count;

    //同步商品总额
    let totalCount = 0;
    for (let i = 0; i < cartProducts.length; i++) {
      if (cartProducts[i].isSelect == 1 && cartProducts[i].isValid == 1) {
        totalCount = totalCount + parseFloat(cartProducts[i].price * cartProducts[i].count);
      }
    }

    //存储编辑商品(用于后台交互)---------------------------------
    cartProducts[index].todo = 0;//todo ==0 只改变了商品的数量
    if (todoList.length == 0) {
      todoList.push(cartProducts[index]);
    } else {
      let find = false;
      for (let t = 0; t < todoList.length; t++) {
        if (todoList[t].id == cartProducts[index].id) {//相等只改变 todo 不添加
          //todoList[t].todo = 0;
          todoList[t] = cartProducts[index]
          find = true;
        }
      }
      if (!find) {//添加到编辑过的商品列表
        todoList.push(cartProducts[index]);
      }
    }
    //更新本地数据------------------------
    this.setData({
      todoList: todoList,
      totalCount: totalCount.toFixed(2),
      cartProducts: cartProducts
    })
    console.log("编辑列表todoList" + todoList);
  },
  addCount: function (e) {//增加单个商品数量
    console.log("增加" + e);
    let count = e.currentTarget.dataset.count;//原购物车商品数量
    let index = e.currentTarget.dataset.index;//商品列表下标
    let cartProducts = this.data.cartProducts;//所有购物车商品
    let todoList = this.data.todoList;//被操作的商品集合
    let stock = cartProducts[index].stock;//当前商品库存
    let [msg, compareNum] = ['', ''];//用于比较的库存数量；
    if (cartProducts[index].isLimited == '1'){
      compareNum = cartProducts[index].canBuyNum;
      msg = '该商品为限购商品，您最多还可购买' + compareNum +"个"
    }else{
      compareNum = stock;
      msg = '商品库存不足';
    }
    if (count < compareNum) {//当前商品数量小于库存
      count = parseInt(count) + 1;
    } else {
      count = compareNum;
      wx.showToast({
        title: msg,
        icon: 'none'
      })
    }
    //改变被选中商品数量
    cartProducts[index].count = count;
    //同步商品总额
    let totalCount = 0;
    for (let i = 0; i < cartProducts.length; i++) {
      if (cartProducts[i].isSelect == 1 && cartProducts[i].isValid == 1) {
        totalCount = totalCount + parseFloat(cartProducts[i].price * cartProducts[i].count);
      }
    }

    //存储编辑商品(用于后台交互)---------------------------------
    cartProducts[index].todo = 0;//todo ==0 只改变了商品的数量
    if (todoList.length == 0) {
      todoList.push(cartProducts[index]);
    } else {
      let find = false;
      for (let t = 0; t < todoList.length; t++) {
        if (todoList[t].id == cartProducts[index].id) {//相等只改变 todo 不添加
          //todoList[t].todo = 0;
          todoList[t] = cartProducts[index]
          find = true;
        }
      }
      if (!find) {//添加到编辑过的商品列表
        todoList.push(cartProducts[index]);
      }
    }
    //更新 编辑列表
    this.setData({
      totalCount: totalCount.toFixed(2),
      cartProducts: cartProducts,
      todoList: todoList,
      compareNum: compareNum

    })
    console.log("编辑列表todoList" + todoList);
  },
  changeCount: function (e) {
    console.log("输入商品数量" + e.detail.value);
    let inputCount = e.detail.value;//输入商品数量
    let index = e.currentTarget.dataset.index;//商品列表下标
    let cartProducts = this.data.cartProducts;//所有购物车商品
    let todoList = this.data.todoList;//被操作的商品集合
    let stock = cartProducts[index].stock;//当前商品库存
    let [msg, compareNum] = ['', ''];//用于比较的库存数量；
    if (cartProducts[index].isLimited == '1') {
      compareNum = cartProducts[index].canBuyNum;
      msg = '该商品为限购商品，您最多还可购买' + compareNum + "个"
    } else {
      compareNum = stock;
      msg = '商品库存不足';
    }
    if (inputCount < 1) {
      inputCount = 1;
      wx.showToast({
        title: '商品数量最小为1',
        icon: 'none'
      })
    } else {
      if (inputCount > compareNum) {
        inputCount = compareNum;
        wx.showToast({
          title:msg,
          icon: 'none'
        })
      }
    }
    //改变被选中商品数量
    cartProducts[index].count = inputCount;
    //同步商品总额
    let totalCount = 0;
    for (let i = 0; i < cartProducts.length; i++) {
      if (cartProducts[i].isSelect == 1 && cartProducts[i].isValid == 1) {
        totalCount = totalCount + parseFloat(cartProducts[i].price * cartProducts[i].count);
      }
    }
    //存储编辑商品(用于后台交互)---------------------------------
    cartProducts[index].todo = 0;//todo ==0 只改变了商品的数量
    if (todoList.length == 0) {
      todoList.push(cartProducts[index]);
    } else {
      let find = false;
      for (let t = 0; t < todoList.length; t++) {
        if (todoList[t].id == cartProducts[index].id) {//相等只改变 todo 不添加
          //todoList[t].todo = 0;
          todoList[t] = cartProducts[index]
          find = true;
        }
      }
      if (!find) {//添加到编辑过的商品列表
        todoList.push(cartProducts[index]);
      }
    }
    //更新 编辑列表
    this.setData({
      totalCount: totalCount.toFixed(2),
      cartProducts: cartProducts,
      todoList: todoList
    })
    console.log("编辑列表todoList" + todoList);
  },
  
  radioSelect: function (e) {//选择单个商品操作
    console.log("选中单个商品下标" + e.currentTarget.dataset.index);
    //获取所选元素下标
    let index = e.currentTarget.dataset.index;//商品列表下标
    let cartProducts = this.data.cartProducts;//所有购物车商品
    let todoList = this.data.todoList;//改动的商品列表
    let isEdit = this.data.isEdit;//是否是编辑状态
    let isCheckedAll = false;//初始化全选状态
    //编辑状态下的失效商品可以选中 参与计数selectnum

    //----------------改变按钮的被选中状态--------------------
    let isSelect = cartProducts[index].isSelect;


    //设置状态
    if (isSelect == 0) {
      cartProducts[index].isSelect = 1
    } else {
      cartProducts[index].isSelect = 0
    }
    //计算选中状态-------------------------------------------------------------------
    let selectNum = 0;//被选中商品的数量
    let disValidNum = 0;//未选中数量
    if (isEdit) {//编辑状态 失效商品可选 
      //对商品数量进行累计
      for (let p = 0; p < cartProducts.length; p++) {
        if (cartProducts[p].isSelect == 1) {
          selectNum = parseInt(selectNum) + 1;
        }
      }
      if (selectNum == cartProducts.length) {
        isCheckedAll = true;
      }
    } else {//未编辑状态  失效商品设置为 isSelect = 0 
      for (let p = 0; p < cartProducts.length; p++) {
        if (cartProducts[p].isValid == 0) {//失效商品不参与计算
          disValidNum = parseInt(disValidNum) + 1;
          cartProducts[p].isSelect = 0;
          continue;
        }
        if (cartProducts[p].isSelect == 1) {
          selectNum = parseInt(selectNum) + 1;
        }
      }
      if (selectNum == parseInt(cartProducts.length - disValidNum)) {
        isCheckedAll = true;
      }
    }

    // //更新商品数据
    this.setData({
      cartProducts: cartProducts
    })
    // //-------------根据是否是编编辑状态获取商品的总额以及改变商品被选状态
    let totalCount = 0;
    for (let p = 0; p < cartProducts.length; p++) {
      if (cartProducts[p].isSelect == 1 && cartProducts[p].isValid == 1) {
        totalCount = totalCount + parseFloat(cartProducts[p].price * cartProducts[p].count);
      }
    }

    // //变更改动的商品列表选中状态----------------------------------------------
    cartProducts[index].todo = 0;
    if (todoList.length == 0) {
      todoList.push(cartProducts[index]);
    } else {
      let find = false
      for (let i = 0; i < todoList.length; i++) {
        if (todoList[i].id == cartProducts[index].id) {//如果列表包含改变选中状态
          todoList[i].isSelect = cartProducts[index].isSelect;
          find = true;
        }
      }
      if (!find) {//如果在todolist中没有找到,则添加该商品
        todoList.push(cartProducts[index]);
      }
    }
    console.log("selectNum" + selectNum);
    console.log("todoList--" + todoList.length);
    this.setData({
      totalCount: totalCount.toFixed(2),
      isCheckedAll: isCheckedAll,
      selectNum: selectNum,
      todoList: todoList
    })
  },

  deleteProducts: function (e) {//批量删除
    console.log("批量删除");
    let that = this;
    let cartProducts = this.data.cartProducts;//所有购物车商品
    let todoList = this.data.todoList;//被操作的商品集合
    let deleteList = [];//剩余商品列表，选中删除列表
    wx.showModal({
      title: '',
      content: '确定要删除所选商品么？',
      cancelText: '我再想想',
      confirmText: '确定',
      success: function (e) {
        if (e.confirm) {
          //选出被选中的待删除列表
          for (let p = 0; p < cartProducts.length; p++) {
            if (cartProducts[p].isSelect == 1) {
              deleteList.push(cartProducts[p]);
            }
          }
          console.log(deleteList);
          //将数组转换为字符串 接收
          let deleteListStr = JSON.stringify(deleteList);
       
          wx.request({
            url: app.data.baseUrl + '/weixin/cart/delete',
            data: {
              deleteList: deleteListStr,
              rdSession: rd_session
            },
            header: {
             'content-type': 'application/x-www-form-urlencoded'
              
             // 'content-type': 'application/json'

            },
            method: 'POST',
            success: function (res) {
              console.log(res);
              if (res.data.ret) {
                //将删除的移除购物车列表 返回商品列表
                let newList = res.data.data.value;
                that.setData({
                  cartProducts: newList,
                  totalCount: 0
                })
                app.getElementsCounts();
              } else {
                wx.showToast({
                  title: '删除失败',
                  icon: 'none',
                  duration: 1500,
                  mask: true
                })
              }
            }
          })
        }
      }
    })
  },

  checkSession: function () {
    let that = this;
    let toPayPage = that.data.toPayPage;
    let isAuthorization = app.data.isAuthorization;
    if (isAuthorization) {
      that.showCartList();
      if (toPayPage) {//跳转待付款订单页
        app.toPayPage(that);
        setTimeout(function () {
          that.setData({
            toPayPage: false,
            isCheckedAll: false,
            selectNum: 0,
            totalCount: 0
          })
        }, 500)
        return;
      }
      //获取购物车列表

    } else {
      app.loginAnimation();
    }
  },
  toPayPage: function (e) {//(结算)提交订单
    let that = this;
    that.data.toPayPage = true;
    that.checkSession();

  },
  //-------登陆动画-------------------
  loginAnimation: function () {
    app.loginAnimation();
    this.setData({
      isAuthorization: app.data.isAuthorization,
      animationData: app.data.animationData,
      showLogin: app.data.showLogin,
    })
  },
  //-------关闭登陆动画--------------
  closeLoginAnimation: function (e) {
    let that = this;
    console.log(e);
    app.closeLoginAnimation(e);
    this.setData({
      isAuthorization: app.data.isAuthorization,
      animationData: app.data.animationData,
      showLogin: app.data.showLogin,
    })
    let toPayPage = that.data.toPayPage;
    setTimeout(function () {
      if (app.data.isAuthorization) {//查看是否登录、授权
        if (toPayPage) {//是否去待付款订单页
          app.toPayPage(e, that);
          //初始化是否去待付款订单页
          setTimeout(function () {
            that.setData({
              toPayPage: false,
              isCheckedAll: false,
              selectNum: 0,
              totalCount: 0
            })
          }, 500)
          return
        }
        that.showCartList();//登录后展示购物车列表
      }
    }, 2000)
  },
  onPullDownRefresh: function () {
    this.setData({
      isAuthorization: app.data.isAuthorization,
      isEdit: false,
      isChecked: false,
      isCheckedAll: false,
      selectNum: 0,//被选中商品数量
      totalCount: 0,//商品总额
    })
    if (app.data.isAuthorization) {
      app.getElementsCounts();
      this.showCartList();
    } else {
      this.checkSession();
    }
    wx.stopPullDownRefresh()
  },
  getFormId: function (e) {
    console.log(e);
    app.getFormId(e);
  },
  //根据商品id 查商品详情
  selectProductById: function (e) {
    console.log('根据商品id 查商品详情参数');
    console.log(e);
    let productId = e.currentTarget.dataset.productid || this.data.productId;
    let that = this;
    console.log(productId);
    this.setData({
      productId: productId,
      pageUrl: '/pages/product/product'
    })
    app.selectProductById(that);
  
  },
})